package cc.messcat.log;

import cc.messcat.common.model.ResponseBean;
import cc.messcat.entity.fupin.Family;
import cc.messcat.entity.fupin.PoorFamily;
import cc.messcat.entity.fupin.PoorVillage;
import cc.messcat.entity.fupin.VisitRecd;
import cc.messcat.entity.helpUnits.HelpUnits;
import cc.messcat.entity.log.Log;
import cc.messcat.entity.system.McUser;
import cc.messcat.service.log.LogService;
import cc.messcat.service.system.UserService;
import cc.messcat.util.IPUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @注释	切点类 
 */
@Aspect
@Component
public class LogAspect {
	@Resource
	private LogService logService;
	@Resource
	private UserService userService;
	
	private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
	
	//以注解切入
	@Pointcut("@annotation(cc.messcat.log.OperationLog)")
	public void controllerAspect(){
	}
	
	@AfterReturning(returning="returnValue",pointcut="controllerAspect()")
	public void doBefore(JoinPoint joinPoint,Object returnValue) throws NoSuchMethodException, SecurityException{
		ServletRequestAttributes attrs =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 
		HttpServletRequest request =  attrs.getRequest();  
		// 获取方法注解内容
		String module = "";
		String desc = "";
		String type = "";
		String param = "";
		try {
			MethodSignature ms = (MethodSignature) joinPoint.getSignature();
			Class cla = joinPoint.getTarget().getClass();
			String backageName = cla.getPackage().getName();
			
			Method method = cla.getMethod(joinPoint.getSignature().getName(),ms.getParameterTypes());
			if(method != null) {
				OperationLog o = method.getAnnotation(OperationLog.class);
				if(o != null) {
					module = o.module();
					desc = o.desc();
					type = StringUtils.isBlank(o.type()) 
						? backageName.contains("system") || backageName.contains("log") ? "系统" : "业务"
						: o.type();
					param = parameterInfo(joinPoint,returnValue,method);
				}
			}
		} catch (Exception e) {
			logger.info("找不到当前方法");
		}
		
        HttpSession session = request.getSession();    
        //读取session中的用户    
		Long userId = (Long) session.getAttribute("userId");
		String userName = null;
		if (userId != null) {
			McUser user = userService.retrieveObject(McUser.class, userId);
			userName = user.getUsername();
		}

		// 请求的IP
		String ip = IPUtil.getIpAddr(request);
		try {
			//数据库日志
			Log log = new Log();
			log.setDescription(StringUtils.isBlank(desc) ? "无记录" : desc + param);
			log.setMethod(StringUtils.isBlank(module) ? "无记录" : module);
			log.setType(StringUtils.isBlank(type) ? "无记录" : type);
			log.setRequestIp(ip);
			log.setParams("");
			log.setUserName(StringUtils.isBlank(userName) ? "" : userName);
			log.setAddTime(new Date());
			// 保存数据库
			logService.addObject(log);
		} catch (Exception e) {
			// 记录本地异常日志
			logger.error("异常信息", e.getMessage());
		}
	}

	/**
	 * 获取参数信息
	 * @param method 
	 * @return
	 */
	private String parameterInfo(JoinPoint jp,Object returnValue, Method method) {
		Object[] args = jp.getArgs();
		
		try {
			if(args != null && args.length > 0) {
				RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
				String value = requestMapping.value()[0];
				value = value.replaceAll("/", "");
				logger.info("url : " + value);
				
				switch (value) {
					//网页端登录
					case "goLoginning" :
						return " {登录用户名="+args[1]+"}";
					
					//app登录
					case "appLogin" :
						return " {登录用户名="+args[1]+"}";
					
					//行政区域删除
					case "delectarea" :
						return " {id="+args[0]+"}";
						
					//自然村添加
					case "addNaVillage" :
					//贫困村添加
					case "addPoorVillage" :
						return  " {id="+((ResponseBean)returnValue).getResult()+"}";
						
					//贫困村，自然村修改
					case "updatePoorVillage" :
					case "updateNaVillage" :
						return " {id="+((PoorVillage)args[0]).getId().toString()+"}";
						
					//删除贫困村
					case "deletePoorVillage" :
					//删除自然村
					case "deletePoorVillages" :
						return " {id="+args[0].toString()+"}";
						
					//贫困户新增
					case "addPoorFamily" :
						return  " {id="+((ResponseBean)returnValue).getResult()+"}";
						
					//贫困户中的家庭成员修改
					case "addOrUpdateFamily" :
						return " {贫困户id="+((Family)args[0]).getFid().toString()+", "
						+(((Family)args[0]).getId() != null ? "被修改家庭成员id=" + ((Family)args[0]).getId() : "新增家庭成员姓名="+((Family)args[0]).getName()) + "}";

					//修改贫困户
					case "updatePoorFamily" :
						return " {贫困户id="+((PoorFamily)args[0]).getId().toString()+"}";
					
					//删除贫困户
					case "deletePoorFamily" :
						return " {id="+args[0]+"}";
						
					//家庭成员删除
					case "deleteFamilyid" :
						return " {id="+args[0]+"}";
					
					//查询贫困户详情
					case "getPoorFamily" :
						return " {id="+args[0]+"}";
					
					//村详情查看
					case "getPoorVillage" :
						return " {id="+args[0]+"}";
						
					//帮扶负责人结对贫困户
					case "associateHP" :
						return " {贫困户id="+args[0]+", 负责人id="+args[1]+"}";
						
					//解除多对多贫困村
					case "addhelpoor" :
						return " {帮扶单位id="+args[0]+", 贫困村id="+args[1]+"}";
						
					//解除多对多贫困村
					case "removeAddhelpoors" :
						return " {帮扶单位id="+args[0]+", 贫困村id="+args[1]+"}";
						
					//添加帮扶记录
					case "addVisitRecd" :
						return " {帮扶记录id="+((ResponseBean)returnValue).getResult()+", 贫困户id="+((VisitRecd)args[0]).getPoorFamily().getId()+"}";
						
					//编辑帮扶记录
					case "editVisitRecd" :
						return " {帮扶记录id="+((VisitRecd)args[0]).getId()+"}";
						
					//删除帮扶记录
					case "deleteVisitRecd" :
						return " {帮扶记录id="+args[0]+"}";
					
					//帮扶单位修改
					case "updatehu" :
						return " {帮扶单位id="+((HelpUnits)args[0]).getId()+"}";

                    //发表工作圈动态
                    case "addCircle" :
                        return "{id="+((ResponseBean)returnValue).getResult()+"}";

                    //删除工作圈动态
                    case "removeCircle" :
                        return "{id="+args[0]+"}";


					default:
				}
			}
		} catch (Exception e) {
			logger.warn("日志参数记录错误");
			e.printStackTrace();
		}
		return "";
	}

}
